import './ChatRoom.css'
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Input, Button, Badge, Avatar, Upload, Tooltip, message, Modal } from 'antd';
import axios from 'axios'
import { SearchOutlined, AudioOutlined, FileImageOutlined, VideoCameraOutlined, SmileOutlined, MoreOutlined, SendOutlined, DownloadOutlined, CloseOutlined, DeleteOutlined, VideoCameraAddOutlined, AudioMutedOutlined } from '@ant-design/icons';
import data from '@emoji-mart/data'
import Peer from 'peerjs';
import Picker from '@emoji-mart/react'

const ChatRoom: React.FC = () => {
  const [selectedContact, setSelectedContact] = useState<string>('');
  const [messageInput, setMessageInput] = useState<string>('');
  const [isVideoModalVisible, setIsVideoModalVisible] = useState<boolean>(false);
  const [isAudioModalVisible, setIsAudioModalVisible] = useState<boolean>(false);
  const [isEmojiModalVisible, setIsEmojiModalVisible] = useState<boolean>(false);
  const [isMuted, setIsMuted] = useState(true);
  const [isVideoDisabled, setIsVideoDisabled] = useState(false);
  const [callDuration, setCallDuration] = useState<number>(0)
  const peerRef = useRef<Peer | null>(null)
  const localStreamRef = useRef<MediaStream | null>(null)
  const remoteStreamRef = useRef<MediaStream | null>(null)
  const audioRef = useRef<HTMLAudioElement | null>(null)
  const localVideoRef = useRef<HTMLVideoElement | null>(null)
  const remoteVideoRef = useRef<HTMLVideoElement | null>(null)
  const baseUrl = 'http://localhost:3000';
  const callStartTimeRef = useRef<number | null>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null)
  const [callActive, setCallActive] = useState<boolean>(false)
  const [dataConnection, setDataConnection] = useState<any>(null);
  const [fileTypeFilter, setFileTypeFilter] = useState<string>('all');
  const currentCallRef = useRef<any>(null)

  //联系人和消息数据
  const [newContacts, setNewContacts] = useState<{
    _id: string;
    name: string;
    avatar: string;
    online: boolean;
    lastMessage: string;
    unread: number;
  }[]>([])
  const [inputValue, setInputValue] = useState<string>('')
  //模拟消息数据
  const [messages, setMessage] = useState<{
    _id: string,
    sender: { _id: string | null; name?: string; avatar?: string },
    receiver: string,
    type: string,
    conversation: string,
    content: string,
    isRead: boolean,
    time: Date
  }[]>([]);
  //模拟共享文件数据
  const [sharedFiles, setSharedFiles] = useState<{
    _id: string;
    name: string;
    type: string;
    size: string;
    url: string;
    uploader: string;
    time: string;
  }[]>([]);

  const senderId = localStorage.getItem('senderId')
  const getUserList = useCallback(async () => {
    const res = await axios.get(`http://localhost:3000/userlist?senderId=${senderId}`)
    setNewContacts(res.data.data)

  }, [senderId])
  const getMessage = useCallback(async () => {
    if (!selectedContact || !senderId) {
      return
    }
    const res = await axios.get(`http://localhost:3000/message?sender=${senderId}&receiver=${selectedContact}`)
    setMessage(res.data.data)

  }, [selectedContact, senderId])
  const getFileType = (file: File): string => {
    if (file.type.startsWith('image')) return 'image';
    if (file.type.startsWith('video')) return 'video';
    if (file.type.startsWith('audio')) return 'audio';
    return 'file';
  };
  const sendMessage = async () => {
    if (!selectedContact || !messageInput.trim()) {
      message.error('请选择联系人或输入内容');
      return;
    }
    const senderId = localStorage.getItem('senderId');
    if (!senderId) {
      message.error('未找到 senderId，请重新登录');
      return;
    }
    try {
      const res = await axios.post('http://localhost:3000/message', {
        senderId,
        receiverId: selectedContact,
        content: messageInput,
        type: 'text',
      });
      if (res.data.code === 200) {
        const newMessage = {
          _id: res.data.data._id,
          sender: { _id: senderId },
          receiver: selectedContact,
          content: messageInput,
          type: 'text',
          time: new Date(res.data.data.timestamp),
          isRead: false,
        };
        setMessage((prev) => [...prev, newMessage]);
        if (dataConnection) {
          dataConnection.send(newMessage);
        }
        setMessageInput('');
      } else {
        message.error(res.data.msg);
      }
      getMessage()
    } catch (err) {
      message.error('发送消息失败:', err);
    }
  };
  useEffect(() => {
    getUserList()
    return () => {
      setNewContacts([])
    }
  }, [senderId])
  useEffect(() => {
    getMessage()
    return () => {
      setMessage([])
    }
  }, [selectedContact])
  useEffect(() => {
    if (selectedContact && dataConnection) {
      axios.get(`http://localhost:3000/message?sender=${senderId}&receiver=${selectedContact}`).then(async (res) => {
        const message = res.data.data
        const unreadMessage = message.filter((m: any) => !m.isRead && m.sender._id !== selectedContact)
        if (unreadMessage.length > 0) {
          await axios.put('http://localhost:3000/message/read', {
            senderId,
            receiverId: selectedContact,
          })
          dataConnection.send({ type: 'read', messageIds: unreadMessage.map((msg: any) => msg._id) })
          getMessage()
        }
        setMessage(message)
      })
    }
  }, [selectedContact])
  useEffect(() => {
    if (isVideoModalVisible && localVideoRef.current && localStreamRef.current) {
      localVideoRef.current.srcObject = localStreamRef.current;
      localVideoRef.current.play().catch(err => console.error('本地视频播放失败:', err));
    }
    if (isVideoModalVisible && remoteVideoRef.current && remoteStreamRef.current) {
      remoteVideoRef.current.srcObject = remoteStreamRef.current;
      remoteVideoRef.current.play().catch(err => console.error('远程视频播放失败:', err));
    }
  }, [isVideoModalVisible, localStreamRef.current, remoteStreamRef.current]);
  useEffect(() => {
    if (isAudioModalVisible && audioRef.current && localStreamRef.current) {
      audioRef.current.srcObject = localStreamRef.current;
      audioRef.current.play().catch(err => console.error('音频播放失败:', err));
    }
  }, [isAudioModalVisible, localStreamRef.current]);
  useEffect(() => {
    if (dataConnection) {
      dataConnection.on('data', (data: any) => {
        if (data.type === 'read') {
          setMessage(prev => prev.map(msg =>
            data.messageIds.includes(msg._id) ? { ...msg, isRead: true } : msg
          ));
        } else if (['text', 'image', 'video', 'audio', 'file', 'call'].includes(data.type)) {
          setMessage((prev) => [...prev, data]);
        }
      });
    }
  }, [dataConnection]);
  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (callActive && currentCallRef.current) {
      interval = setInterval(() => {
        setCallDuration(Math.floor((Date.now() - callStartTimeRef.current!) / 1000))
      }, 1000)
    }
    return () => {
      if (interval) clearInterval(interval)
    }
  }, [callActive])
  //初始化peer
  useEffect(() => {
    if (!senderId) {
      message.error('请先登录');
      return;
    }

    // 创建 PeerJS 实例
    const peer = new Peer(senderId, { host: 'localhost', port: 9000, path: '/myapp' });
    peerRef.current = peer;

    // PeerJS 连接成功
    peer.on('open', (id) => {
      console.log(`PeerJS 连接成功，ID: ${id}`);
    });

    // 处理接收到的通话
    peer.on('call', (call) => {
      console.log(`收到${call.metadata.type}通话请求，来自: ${call.peer}`);
      setCallActive(true)
      callStartTimeRef.current = Date.now()
      navigator.mediaDevices.getUserMedia({ audio: true, video: call.metadata.type === 'video' }) // 请求音视频权限
        .then((stream) => {
          localStreamRef.current = stream;
          call.answer(stream); // 应答通话
          if (call.metadata.type === 'video') {
            setIsVideoModalVisible(true); // 显示视频通话弹窗
            if (localVideoRef.current) {
              localVideoRef.current.srcObject = stream;
              localVideoRef.current.play().catch((err) => console.error('本地视频播放失败:', err));
            }
          } else {
            setIsAudioModalVisible(true); // 显示语音通话弹窗
          }
          currentCallRef.current = call; // 保存通话对象

          // 播放远程音视频
          call.on('stream', (remoteStream) => {
            remoteStreamRef.current = remoteStream;
            if (call.metadata.type === 'video' && remoteVideoRef.current) {
              remoteVideoRef.current.srcObject = remoteStream;
              remoteVideoRef.current.play().catch((err) => console.error('远程视频播放失败:', err));
            } else if (call.metadata.type === 'audio' && audioRef.current) {
              audioRef.current.srcObject = remoteStream;
              audioRef.current.play().catch((err) => {
                console.error('播放远程音频失败:', err);
                message.error('无法播放音频，请检查设备');
              });
            }
          });

          // 通话被远程关闭
          call.on('close', () => {
            console.log('通话被对方关闭');
            endCall(call.metadata.type);
          });

          // 通话错误
          call.on('error', (err) => {
            console.error('通话错误:', err);
            message.error('通话失败，请重试');
            endCall(call.metadata.type);
          });

          // 通知后端通话已连接
          axios
            .post(`${baseUrl}/call`, {
              senderId,
              receiverId: call.peer,
              type: call.metadata.type,
              status: 'connected',
            })
            .catch((err) => console.error('更新通话状态失败:', err));
        })
        .catch((err) => {
          console.error('无法访问麦克风/摄像头:', err);
          if (call.metadata.type === 'video') {
            setIsVideoModalVisible(true); // Show video modal even if camera fails
            message.warning('无法访问摄像头，将仅启用音频通话');
            navigator.mediaDevices.getUserMedia({ audio: true })
              .then((stream) => {
                localStreamRef.current = stream;
                call.answer(stream);
                currentCallRef.current = call;
              })
              .catch((audioErr) => {
                console.error('无法访问麦克风:', audioErr);
                message.error('无法访问麦克风，请检查权限');
                endCall(call.metadata.type);
              });
          } else {
            message.error('无法访问麦克风，请检查权限');
            endCall(call.metadata.type);
          }
        });
    });

    // 处理 PeerJS 错误
    peer.on('error', (err) => {
      console.error('PeerJS 错误:', err);
      message.error('连接错误，请重试');
    });

    // 组件卸载时清理
    return () => {
      console.log('清理 PeerJS');
      if (peerRef.current) {
        peerRef.current.destroy();
        peerRef.current = null;
      }
      endCall('audio'); // 默认清理音频（确保无残留）
      endCall('video'); // 默认清理视频（确保无残留）
    };
  }, [senderId]);
  const startCall = async (type: 'audio' | 'video') => {
    if (!selectedContact) {
      message.error('请选择一个联系人');
      return;
    }
    if (!peerRef.current) {
      message.error('连接未就绪，请稍后重试');
      return;
    }

    try {
      // 获取音视频流
      const constraints = type === 'video' ? { audio: true, video: true } : { audio: true };
      const stream = await navigator.mediaDevices.getUserMedia(constraints);
      localStreamRef.current = stream;
      callStartTimeRef.current = Date.now()
      setCallActive(true)
      // 设置本地视频（仅视频通话）
      if (type === 'video') {
        setIsVideoModalVisible(true);
        if (localVideoRef.current) {
          localVideoRef.current.srcObject = stream;
          localVideoRef.current.play().catch((err) => console.error('本地视频播放失败:', err));
        }
      } else {
        setIsAudioModalVisible(true);
      }

      // 发起通话
      const call = peerRef.current.call(selectedContact, stream, { metadata: { type } });
      currentCallRef.current = call; // 保存通话对象
      // 通知后端通话已发起
      await axios.post(`${baseUrl}/call`, {
        senderId,
        receiverId: selectedContact,
        type,
        status: 'initiated',
      });

      // 设置30秒超时
      const callTimeout = setTimeout(async () => {
        if (callActive && !remoteStreamRef.current) {
          message.error('对方无应答');
          endCall(type);
          await axios.post(`${baseUrl}/call`, {
            senderId,
            receiverId: selectedContact,
            type,
            status: 'missed',
          });
        }
      }, 30000);

      // 对方接听后播放远程流
      call.on('stream', async (remoteStream) => {
        clearTimeout(callTimeout);
        remoteStreamRef.current = remoteStream;
        if (type === 'video' && remoteVideoRef.current) {
          remoteVideoRef.current.srcObject = remoteStream;
          remoteVideoRef.current.play().catch((err) => console.error('远程视频播放失败:', err));
        } else if (type === 'audio' && audioRef.current) {
          audioRef.current.srcObject = remoteStream;
          audioRef.current.play().catch((err) => console.error('播放远程音频失败:', err));
        }
        await axios.post(`${baseUrl}/call`, {
          senderId,
          receiverId: selectedContact,
          type,
          status: 'connected',
        });
      });

      // 通话关闭
      call.on('close', async () => {
        clearTimeout(callTimeout);
        endCall(type);
        await axios.post(`${baseUrl}/call`, {
          senderId,
          receiverId: selectedContact,
          type,
          status: 'ended',
        });
      });

      // 通话错误
      call.on('error', async (err) => {
        clearTimeout(callTimeout);
        console.error('通话错误:', err);
        message.error('通话失败，请重试');
        endCall(type);
        await axios.post(`${baseUrl}/call`, {
          senderId,
          receiverId: selectedContact,
          type,
          status: 'declined',
        });
      });
    } catch (err) {
      console.error(`无法发起${type === 'video' ? '视频' : '语音'}通话:`, err);
      if (type === 'video') {
        setIsVideoModalVisible(true); // Show video modal even if camera fails
        message.warning('无法访问摄像头，将仅启用音频通话');
        navigator.mediaDevices.getUserMedia({ audio: true })
          .then((stream) => {
            localStreamRef.current = stream;
            setCallActive(true);
            callStartTimeRef.current = Date.now();
            const call = peerRef.current!.call(selectedContact, stream, { metadata: { type: 'video' } });
            currentCallRef.current = call;
            if (localVideoRef.current) {
              localVideoRef.current.srcObject = null; // No video stream
            }
          })
          .catch((audioErr) => {
            console.error('无法访问麦克风:', audioErr);
            message.error('无法访问麦克风，请检查权限');
            endCall('video');
          });
      } else {
        message.error('无法访问麦克风，请检查权限');
      }
    }
  };
  useEffect(() => {
    if (selectedContact) {
      getSharedFiles()
    }
  }, [selectedContact, fileTypeFilter])

  const endCall = async (type: 'audio' | 'video') => {
    console.log(`正在结束${type === 'video' ? '视频' : '语音'}通话...`);
    if (type !== 'audio' && type !== 'video') {
      console.error('无效的 type 值:', type);
      message.error('通话类型错误，请重试');
      return;
    }

    if (localStreamRef.current) {
      localStreamRef.current.getTracks().forEach((track) => {
        track.stop();
        console.log('已停止本地轨道:', track.id, track.kind);
      });
      localStreamRef.current = null;
    }

    if (remoteStreamRef.current) {
      remoteStreamRef.current.getTracks().forEach((track) => {
        track.stop();
        console.log('已停止远程轨道:', track.id, track.kind);
      });
      remoteStreamRef.current = null;
    }

    if (audioRef.current) {
      audioRef.current.srcObject = null;
      audioRef.current.pause();
    }
    if (localVideoRef.current) {
      localVideoRef.current.srcObject = null;
      localVideoRef.current.pause();
    }
    if (remoteVideoRef.current) {
      remoteVideoRef.current.srcObject = null;
      remoteVideoRef.current.pause();
    }

    if (currentCallRef.current) {
      try {
        currentCallRef.current.close();
        console.log('已关闭 PeerJS 通话');
      } catch (err) {
        console.error('关闭 PeerJS 通话失败:', err);
      }
      currentCallRef.current = null;
    }

    if (senderId && selectedContact) {
      try {
        const requestBody = {
          senderId,
          receiverId: selectedContact,
          type,
          status: 'ended',
          duration: callStartTimeRef.current ? Math.floor((Date.now() - callStartTimeRef.current) / 1000) : 0,
        };
        console.log('发送结束通话请求:', requestBody);
        await axios.post(`${baseUrl}/call`, requestBody);
        console.log('已通知后端：通话结束');
      } catch (err) {
        console.error('通知后端通话结束失败:', err);
        message.error('无法更新通话状态，请稍后重试');
      }
    }

    setCallActive(false);
    setIsAudioModalVisible(false);
    setIsVideoModalVisible(false);
    setIsMuted(true);
    setIsVideoDisabled(false);
    setCallDuration(0);
    callStartTimeRef.current = null;
  };
  const getSharedFiles = useCallback(async () => {
    if (!senderId || !selectedContact) return;
    try {
      const params = { senderId, selectedContact };
      params['type'] = fileTypeFilter
      try {
        const conversationRes = await axios.get(`http://localhost:3000/conversation?senderId=${senderId}&receiverId=${selectedContact}`);
        if (conversationRes.data.code === 200 && conversationRes.data.data?._id) {
          params['conversationId'] = conversationRes.data.data._id;
        } else {
          console.warn('未找到会话，返回空列表');
          setSharedFiles([]);
          return;
        }
      } catch (err) {
        console.error('获取会话失败:', err);
        message.error('无法获取会话信息');
        setSharedFiles([]);
        return;
      }
      const res = await axios.get('http://localhost:3000/sharedFiles', { params });
      console.log('共享文件响应:', res.data);
      setSharedFiles(res.data.data || []);
    } catch (err) {
      console.error('获取共享文件失败:', err);
      message.error('获取共享文件失败');
      setSharedFiles([]);
    }
  }, [senderId, selectedContact, fileTypeFilter]);
  const handleFileUpload = async (file: File) => {
    if (!selectedContact) {
      message.error('请选择联系人');
      return false;
    }
    const fileType = getFileType(file);
    if (fileType === 'image' && !['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
      message.error('仅支持 JPEG、JPG、PNG、GIF 或 WEBP 格式的图片');
      return false;
    }
    const formData = new FormData();
    formData.append('file', file);
    formData.append('senderId', senderId!);
    formData.append('receiverId', selectedContact);
    formData.append('type', fileType);
    formData.append('content', `${fileType} message`);
    console.log('上传 FormData:', [...formData.entries()]);
    try {
      const res = await axios.post('http://localhost:3000/message', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      if (res.data.code === 200) {
        const newMessage = {
          _id: res.data.data._id,
          sender: { _id: senderId },
          receiver: selectedContact,
          content: res.data.data.content,
          type: fileType,
          time: new Date(res.data.data.timestamp),
          isRead: false,
        };
        setMessage((prev) => [...prev, newMessage]);
        if (dataConnection) {
          dataConnection.send(newMessage);
        }
        getSharedFiles()
      } else {
        message.error(res.data.msg);
      }
      getMessage()
    } catch (err) {
      console.error('上传失败:', err);
      message.error('上传失败，请检查网络或文件格式');
    }
    return false;
  };
  const toggleMute = () => {
    if (localStreamRef.current) {
      const audioTrack = localStreamRef.current.getAudioTracks()[0];
      if (audioTrack) {
        audioTrack.enabled = !audioTrack.enabled; // 切换静音
        setIsMuted(!audioTrack.enabled);
        message.info(audioTrack.enabled ? '麦克风已开启' : '麦克风已静音');
      } else {
        message.error('未找到音频轨道');
      }
    } else {
      message.error('当前无活跃通话');
    }
  };

  // 切换视频开关状态
  const toggleVideo = () => {
    if (localStreamRef.current) {
      const videoTrack = localStreamRef.current.getVideoTracks()[0];
      if (videoTrack) {
        videoTrack.enabled = !videoTrack.enabled; // 切换视频
        setIsVideoDisabled(!videoTrack.enabled);
        message.info(videoTrack.enabled ? '摄像头已开启' : '摄像头已关闭');
      } else {
        message.error('未找到视频轨道');
      }
    } else {
      message.error('当前无活跃通话');
    }
  };
  const formatDuration = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <div className="flex h-screen bg-gray-100 p-4">
      {/* 联系人列表 */}
      <div className="w-80 bg-white rounded-lg shadow-lg mr-4 flex flex-col">
        <div className="p-4 border-b">
          <Input
            prefix={<SearchOutlined className="text-gray-400" />}
            placeholder="搜索联系人"
            className="rounded-lg"
            onChange={(e) => {
              setInputValue(e.target.value);
            }}
            onKeyUp={(e) => {
              if (e.key == 'Enter') {
                const filterContacts = newContacts.filter(c => c.name.includes(inputValue.trim()));
                setNewContacts(filterContacts);
              }
              if (!inputValue.trim()) {
                getUserList();
              }
            }}
          />
        </div>
        <div className="flex-1 overflow-y-auto">
          {newContacts.filter(c => c._id != senderId).map((contact) => (
            <div
              key={contact._id}
              className={`flex items-center p-4 hover:bg-gray-50 cursor-pointer ${selectedContact === contact._id ? 'bg-blue-50' : ''}`}
              onClick={() => setSelectedContact(contact._id)}
            >
              <div className="relative">
                <Avatar src={contact.avatar} size={48} />
                {contact.online && (
                  <div className="absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-white"></div>
                )}
              </div>
              <div className="ml-3 flex-1">
                <div className="flex justify-between">
                  <span className="font-medium">{contact.name}</span>
                  {contact.unread > 0 && (
                    <Badge count={contact.unread} />
                  )}
                </div>
                <p className="text-gray-500 text-sm truncate">{contact.lastMessage}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
      {/* 聊天主区域 */}
      <div className="flex-1 bg-white rounded-lg shadow-lg mr-4 flex flex-col">
        <div className="p-4 border-b flex items-center">
          <Avatar src={newContacts.find(c => c._id === selectedContact)?.avatar} size={40} />
          <span className="ml-3 font-medium">{newContacts.find(c => c._id === selectedContact)?.name}</span>
        </div>
        <div className="flex-1 overflow-y-auto p-4 bg-gray-50">
          {messages.map(message => (
            <div key={message._id} className={`flex mb-4 ${message.sender._id === senderId ? 'justify-end' : 'justify-start'}`}>
              <div className={`max-w-[70%] ${message.sender._id === senderId ? 'bg-blue-500 text-white' : 'bg-white'} rounded-lg p-3 shadow`}>
                {message.type === 'text' ? (
                  <p>{message.content}</p>
                ) : message.type === 'image' ? (
                  <img src={`${baseUrl}${message.content}`} alt="上传的图片" className="max-w-full rounded-lg" />
                ) : message.type === 'video' ? (
                  <video src={`${baseUrl}${message.content}`} controls className="max-w-full rounded-lg" />
                ) : message.type === 'audio' ? (
                  <audio src={`${baseUrl}${message.content}`} controls className="max-w-full rounded-lg" />
                ) : message.type === 'call' ? (
                  <p className="text-sm italic">{message.content || '通话消息为空'}</p>
                ) : (
                  <a href={`${baseUrl}${message.content}`} download>{message.content.split('/').pop()}</a>
                )}
                <div className={`text-xs mt-1 ${message.sender._id === senderId ? 'text-blue-100' : 'text-gray-400'}`}>
                  {new Date(message.time).toLocaleString()}
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className="p-4 border-t">
          <div className="flex items-center mb-4">
            <Tooltip title="语音通话">
              <Button type="text" icon={<AudioOutlined />} className="!rounded-button" onClick={() => startCall('audio')} disabled={callActive} />
            </Tooltip>
            <Tooltip title="选择附件">
              <Upload beforeUpload={handleFileUpload} showUploadList={false}>
                <Button type="text" icon={<FileImageOutlined />} className="!rounded-button" />
              </Upload>
            </Tooltip>
            <Tooltip title="视频通话">
              <Button type="text" icon={<VideoCameraOutlined />} className="!rounded-button" onClick={() => startCall('video')} disabled={callActive} />
            </Tooltip>
            <Tooltip title="表情">
              <Button type="text" icon={<SmileOutlined />} className="!rounded-button" onClick={() => setIsEmojiModalVisible(true)} />
            </Tooltip>
            <Tooltip title="更多">
              <Button type="text" icon={<MoreOutlined />} className="!rounded-button" />
            </Tooltip>
          </div>
          <div className="flex">
            <Input.TextArea
              value={messageInput}
              onChange={e => setMessageInput(e.target.value)}
              placeholder="输入消息..."
              autoSize={{ minRows: 1, maxRows: 4 }}
              className="mr-2"
            />
            <Button type="primary" icon={<SendOutlined />} className="!rounded-button whitespace-nowrap" onClick={sendMessage}>
              发送
            </Button>
          </div>
        </div>
      </div>
      {/* 文件共享面板 */}
      <div className="w-80 bg-white rounded-lg shadow-lg flex flex-col">
        <div className="p-4 border-b flex space-x-2">
          <Button
            type={fileTypeFilter === 'all' ? 'primary' : 'text'}
            className="!rounded-button whitespace-nowrap"
            onClick={() => setFileTypeFilter('all')}
          >
            全部
          </Button>
          <Button
            type={fileTypeFilter === 'image' ? 'primary' : 'text'}
            className="!rounded-button whitespace-nowrap"
            onClick={() => setFileTypeFilter('image')}
          >
            图片
          </Button>
          <Button
            type={fileTypeFilter === 'file' ? 'primary' : 'text'}
            className="!rounded-button whitespace-nowrap"
            onClick={() => setFileTypeFilter('file')}
          >
            文件
          </Button>
          <Button
            type={fileTypeFilter === 'video' ? 'primary' : 'text'}
            className="!rounded-button whitespace-nowrap"
            onClick={() => setFileTypeFilter('video')}
          >
            视频
          </Button>
        </div>
        <div className="flex-1 overflow-y-auto">
          {sharedFiles.length === 0 ? (
            <div className="p-4 text-center text-gray-500">暂无共享文件</div>
          ) : (
            sharedFiles.map(file => (
              <div key={file._id} className="p-4 hover:bg-gray-50 border-b">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center">
                    {file.type === 'image' && <FileImageOutlined className="text-blue-500 mr-2" />}
                    {file.type === 'video' && <VideoCameraOutlined className="text-green-500 mr-2" />}
                    {file.type === 'document' && <FileImageOutlined className="text-orange-500 mr-2" />}
                    <span className="font-medium truncate">{file.name}</span>
                  </div>
                  <Tooltip title="下载">
                    <Button
                      type="text"
                      icon={<DownloadOutlined />}
                      className="!rounded-button"
                      onClick={() => window.open(`${baseUrl}${file.url}`, '_blank')}
                    />
                  </Tooltip>
                </div>
                <div className="text-sm text-gray-500">
                  <span>{file.uploader}</span>
                  <span className="mx-2">·</span>
                  <span>{file.size}</span>
                  <span className="mx-2">·</span>
                  <span>{file.time}</span>
                </div>
              </div>
            ))
          )}
        </div>
      </div>

      {/* 表情弹窗 */}
      <Modal
        title="选择表情"
        open={isEmojiModalVisible}
        footer={null}
        onCancel={() => setIsEmojiModalVisible(false)}
        width={400}
        centered
      >
        <Picker data={data} onEmojiSelect={(emoji: { native: string }) => {
          console.log(emoji.native)
          setMessageInput(pre => pre + emoji.native)
          setIsEmojiModalVisible(false)
        }}> </Picker>
      </Modal>

      {/* 视频通话弹窗 */}
      <Modal
        title={`视频通话-${callActive ? `通话中(${formatDuration(callDuration)})` : '正在连接...'}`}
        open={isVideoModalVisible}
        footer={null}
        onCancel={() => { endCall('video') }}
        width={800}
        centered
        styles={{ body: { padding: 0 } }}
        closable={false}
      >
        <div className="relative bg-gray-900 h-[600px] rounded-lg overflow-visible">
          <div className="absolute top-4 right-4 z-10">
            <Button
              type="primary"
              shape="circle"
              icon={<CloseOutlined />}
              onClick={() => { endCall('video') }}
              className="bg-gray-800 border-none hover:bg-gray-700"
            />
          </div>

          <div className="absolute inset-0 flex items-center justify-center">
            {remoteStreamRef.current ? (
              <video ref={remoteVideoRef} autoPlay muted className="w-full h-full object-cover" />
            ) : (
              <Avatar size={80} src={newContacts.find((c) => c._id === selectedContact)?.avatar} />
            )}
          </div>
          <div className="absolute bottom-8 right-8 w-48 h-36 bg-gray-800 rounded-lg overflow-hidden">
            {localStreamRef.current && localStreamRef.current.getVideoTracks().length > 0 ? (
              <video ref={localVideoRef} autoPlay muted className="w-full h-full object-cover" />
            ) : (
              <Avatar size={80} src={newContacts.find((c) => c._id === senderId)?.avatar} className="m-auto mt-4" />
            )}
          </div>
          <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 flex space-x-4">
            <Button type="primary" danger className="!rounded-button whitespace-nowrap" onClick={() => { endCall('video') }}>
              结束通话
            </Button>
            <Button
              type={isMuted ? 'dashed' : 'primary'}
              icon={isMuted ? <AudioMutedOutlined /> : <AudioOutlined />}
              onClick={toggleMute}
            >
              {isMuted ? '静音' : '取消静音'}
            </Button>
            <Button
              icon={isVideoDisabled ? <VideoCameraAddOutlined /> : <VideoCameraOutlined />}
              onClick={toggleVideo}
            >
              {isVideoDisabled ? '开启视频' : '关闭视频'}
            </Button>
          </div>
        </div>
      </Modal>
      {/* 语音通话弹窗 */}
      <Modal
        title={`语音通话 - ${callActive ? `通话中 (${formatDuration(callDuration)})` : '正在连接...'}`}
        open={isAudioModalVisible}
        footer={null}
        onCancel={() => endCall('audio')}
        width={400}
        centered
      >
        <div className="p-4 text-center">
          <Avatar size={80} src={newContacts.find((c) => c._id === selectedContact)?.avatar} className="mb-4" />
          <p className="text-lg font-medium">{newContacts.find((c) => c._id === selectedContact)?.name}</p>
          <p className="text-gray-400">{callActive ? `通话中... (${formatDuration(callDuration)})` : '正在连接...'}</p>
          <audio ref={audioRef} autoPlay />
          <div className="flex justify-center space-x-4 mt-4">
            <Button
              type="primary"
              danger
              className="!rounded-button whitespace-nowrap"
              onClick={() => endCall('audio')}
            >
              结束通话
            </Button>
            <Button
              type={isMuted ? 'dashed' : 'primary'}
              icon={isMuted ? <AudioMutedOutlined /> : <AudioOutlined />}
              onClick={toggleMute}
            >
              {isMuted ? '静音' : '取消静音'}
            </Button>
            <Button
              className="!rounded-button whitespace-nowrap"
              onClick={() => startCall('audio')}
            >
              重试通话
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};
export default ChatRoom
